package com.heima.schedule.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskInfoLogsMapper;
import com.heima.schedule.mapper.TaskInfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;

import org.apache.logging.log4j.core.util.Cancellable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired(required = false)
    TaskInfoMapper taskInfoMapper;

    @Autowired(required = false)
    TaskInfoLogsMapper taskInfoLogsMapper;

    @Autowired
    RedisCacheService redisCacheService;

    @Autowired
    private ThreadPoolTaskExecutor threaPool;


    @Override
    public long addTask(Task task) {
        Future<Long> future = threaPool.submit(() -> {
            Boolean b = addTaskForDB(task);
            //判断是否添加成功如果成功将任务缓存在数据redis中
            if (b) {
                addTaskForRedis(task);
            }

            return task.getTaskId();
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     *将执行时间小于五分钟的任务添加到redis中
     * @return
     */
    private void addTaskForRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        //判断执行时间
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            //执行时间小于当前时间
            redisCacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSONObject.toJSONString(task));
        }
        //执行时间大于当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long timeInMillis = calendar.getTimeInMillis();
        if(task.getExecuteTime()< timeInMillis&&System.currentTimeMillis()<task.getExecuteTime()){
            redisCacheService.zAdd(ScheduleConstants.FUTURE + key, JSONObject.toJSONString(task),task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    private Boolean addTaskForDB(Task task) {
        Boolean flag=false;
        if(task!=null){
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            //将时间转换后放入到taskinfo中
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            //添加任务何任务日志到数据库
            taskInfoMapper.insert(taskinfo);
            task.setTaskId(taskinfo.getTaskId());
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskInfoLogsMapper.insert(taskinfoLogs);
            flag=true;
        }
        return flag;

    }


    @Override
    public ResponseResult cancelTask(long taskId) {
        Boolean flag=false;
        //更新数据库数据
        Task task=cancelTaskDb(taskId,ScheduleConstants.CANCELLED);
        if(task!=null){
            cancelTaskRedis(task);
            flag=true;
        }
        return ResponseResult.okResult(true);
    }

    private void cancelTaskRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            redisCacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSONObject.toJSONString(task));
        }else {
            redisCacheService.zRemove(ScheduleConstants.FUTURE+key, JSONObject.toJSONString(task));
        }
    }

    private Task cancelTaskDb(long taskId,int status) {
        taskInfoMapper.deleteById(taskId);
        TaskinfoLogs taskinfoLogs = taskInfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs,task);
        taskInfoLogsMapper.updateById(taskinfoLogs);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        return task;
    }


    /**
     * 消费任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key=type+"_"+priority;
        String taskJson = redisCacheService.lRightPop(ScheduleConstants.TOPIC + key);
        Task task=null;
        if(StringUtils.isNotBlank(taskJson)){
            task= JSONObject.parseObject(taskJson,Task.class);
            task=cancelTaskDb(task.getTaskId(), ScheduleConstants.EXECUTED);
        }
        return task;
    }


    @Scheduled(cron = "0 0/1 * * * ?")
    public void refresh() {
        threaPool.execute(() -> {
            log.info("未来任务开始刷新到新的队列中");
            Set<String> futureKeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");
            //遍历futureKeys
            futureKeys.forEach(item->{
                Set<String> tasks = redisCacheService.zRangeByScore(item, 0, System.currentTimeMillis());
                if(!tasks.isEmpty()){
                    String topicKey = ScheduleConstants.TOPIC + item.split(ScheduleConstants.FUTURE)[1];
                    redisCacheService.refreshWithPipeline(item,topicKey,tasks);
                    log.info("成功的将"+item+"刷新到了"+topicKey);
                }
            });
        });
    }


    @Scheduled(cron = "0/5 * * * * ?")
    @PostConstruct
    public void reloadData(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 5);
        List<Taskinfo> list = taskInfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                .le(Taskinfo::getExecuteTime, calendar.getTimeInMillis()));
        list.forEach(item->{
            Task task = new Task();
            BeanUtils.copyProperties(item,task);
            task.setExecuteTime(item.getExecuteTime().getTime());
            //防止重复消费先删除两个队列中的缓存
            //clearCache();
            addTaskForRedis(task);
        });
    }


    private void clearCache(){
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futurekeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topickeys = redisCacheService.scan(ScheduleConstants.TOPIC + "*");// topic_
        redisCacheService.delete(futurekeys);
        redisCacheService.delete(topickeys);
    }


}